package com.atguigu.day08;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

public class Flink01_Timer_Exec {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        //2.从端口读取数据
        DataStreamSource<String> streamSource = env.socketTextStream("localhost", 9999);


        //3.将数据转为JavaBean
        SingleOutputStreamOperator<WaterSensor> waterSensorStream = streamSource.map(new MapFunction<String, WaterSensor>() {
            @Override
            public WaterSensor map(String value) throws Exception {
                String[] split = value.split(",");
                return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
            }
        });


        KeyedStream<WaterSensor, Tuple> keyedStream = waterSensorStream.keyBy("id");

        //监控水位传感器的水位值，如果水位值在五秒钟之内连续上升，则报警，并将报警信息输出到侧输出流。
        /**
         * 判断什么  水位是否上升  定时器是否注册
         * 保存什么  上一次的水位  定时器时间
         * 更新是很么 水位  定时器时间
         */
        SingleOutputStreamOperator<String> result = keyedStream.process(new KeyedProcessFunction<Tuple, WaterSensor, String>() {

            //上一次的水位
            private Integer lastVc = Integer.MIN_VALUE;

            //定时器的时间
            private Long timer = Long.MIN_VALUE;

            @Override
            public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {
                //1.判断水位是否上升
                if (value.getVc() > lastVc) {
                    //水位上升
                    //2.判断之前是否已经注册过定时器
                    if (timer == Long.MIN_VALUE) {
                        //没有注册定时器则注册新的定时器
                        timer = ctx.timerService().currentProcessingTime() + 5000;
                        System.out.println("注册定时器：" + ctx.getCurrentKey());
                        ctx.timerService().registerProcessingTimeTimer(timer);
                    }
                } else {
                    //水位没有上升
                    if (timer != Long.MIN_VALUE) {
                        //删除定时器
                        System.out.println("删除定时器：" + ctx.getCurrentKey() );
                        ctx.timerService().deleteProcessingTimeTimer(timer);
                        //重置定时器时间
//                        System.out.println("删除的时候重置定时器");
                        timer = Long.MIN_VALUE;
                    }
                }

                //无论水位是否上升还是下降都要将当前水位保存到上一次水位中以便下一条数据来的时候做判断
                lastVc = value.getVc();
            }

            @Override
            public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
                //获取到侧输出流
                ctx.output(new OutputTag<String>("warning") {
                }, "警报！！！！水位5s内连续上升");

                //重置定时器时间 以便后面的数据来的时候注册新的定时器
//                System.out.println("报警的时候重置定时器");
                timer = Long.MIN_VALUE;
            }
        });
        result.getSideOutput(new OutputTag<String>("warning") {
        }).print();


        env.execute();
    }
}
